var Q = require('q'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    workController = require('../../../CBO/server/controllers/Work.server.controller'),
    enumController = require('../../../QC/server/controllers/Enum.server.controller'),
    extendEnumController = require('../../../SystemManage/server/controllers/ExtendEnum.server.controller');
//通过Barcode获取条码主档信息(打印)
exports.getBarcodeData = function (req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode;
    barcodeMasterController.findBarcodeMaster(Barcode, function (err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });
};
//通过Barcode获取条码主档信息(不良品检验)
exports.getBarcodeDataCheck = function (req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode;
    barcodeMasterController.findBarcodeMasterByBarcode(Barcode, function (err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });
};

//根据code,获取枚举列表
exports.getExtendEnumByCode = function(req, res){
    var parameter = req.body.Parameter,
        code = parameter.code;
    extendEnumController.findByCode(code, function(err, data) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });   
        }
        else{
            res.json({
                Data: data.Options,
                Error: null
            });
        }
        
    });

}

//传入不良类型或不良位置的id，判断是哪类id
exports.getIdType = function(req, res){
    var parameter = req.body.Parameter,
        _id = parameter._id;
    extendEnumController.findByCode('BadType', function(err, data) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        for (var j = 0; j < data.Options.length; j++) {
            if (data.Options[j]._id == _id) {
                res.json({
                    Data: "BadType",
                    Error: null
                });
                return;
            }
        }
        if (j==data.Options.length){
            extendEnumController.findByCode('BadPosition', function(err, data) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                    return;
                }
                for (var i = 0; i < data.Options.length; i++) {
                    if (data.Options[i]._id == _id) {
                        res.json({
                            Data: "BadPosition",
                            Error: null
                        });
                        return;
                    }
                }
                if(i==data.Options.length){
                    res.json({
                        Data: "None",
                        Error: err
                    });
                }
            });
        }
               
    });

}

//更新流水的采集时间、用户信息，删除原品质记录并重新创建。更新主档的用户
exports.updateBadData = function (req, res) {
    var parameter = req.body.Parameter,
        UserId = parameter.User,
        BarcodeId = parameter.BarcodeId,
        Barcode = parameter.Barcode,
        badRecords = parameter.badRecords,
        QCStatus = parameter.QCStatus,
        oldQCStatus = parameter.oldQCStatus,
        BizRecordId = parameter.BizRecord,
        ReworkQty = parameter.ReworkQty,
        workId = parameter.workId,
        ItemMaster = parameter.ItemMaster;

    var dateNow = Date.now();
    var updatebizRecord = {
        Users: [UserId],
        CollectDateTime: dateNow
    };
    

    //更新流水采集时间，用户
    bizRecordController.updateBizRecordByValue(BizRecordId, updatebizRecord, function (err, record) {
        if (err) {
            
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            
            //删除QC记录
            qcRecordController.deleteQCRecords(BizRecordId, function (err, result) {
                if (err) {
                    
                    res.json({
                        Data: null,
                        Error: err
                    });
                }
                else {
                    
                    //添加QC记录
                    qcRecordController.addQCRecords(BizRecordId, badRecords, function (err, result) {
                        if (err) {
                            
                            res.json({
                                Data: null,
                                Error: err
                            });
                        }
                        else{
                            
                            //根据物料和作业查找工序
                            operationController.findByItemMasterAndWork(ItemMaster, workId, function (err, operationRecord) {
                                if (err) {
                                    console.log(err);
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                }
                                else {
                                    
                                    if (operationRecord == null) {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '查询工序失败';
                                        newErr.message = '该物料没有找到对应作业的工序！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    }
                                    else {
                                        var updateRecord = {
                                            Users: [UserId],
                                            QCStatus: QCStatus     
                                        };
                                        if(oldQCStatus!=4&&QCStatus===4){
                                            
                                            updateRecord.QCReworkOperation = operationRecord._id;
                                            // updateRecord.ReworkQty = ReworkQty+1;
                                            updateRecord.ReworkQty = ReworkQty ? ReworkQty+1 : 1;
                                        }
                                        // console.log(updateRecord);
                                        //更新主档信息
                                        barcodeMasterController.updateByValue(Barcode, updateRecord, function (err, result) {
                                            if (err) {
                                                res.json({
                                                    Data: null,
                                                    Error: err
                                                });
                                            }
                                            else {
                                                if (result.ok === 1) {
                                                    res.json({
                                                        Data: true,
                                                        Error: null
                                                    });
                                                }
                                            }

                                        });
                       
                                    }
                                }
                            });

                            
                        }
                        
                    });
                }
            });
        }

    });
};


//通过Barcode获取检验作业条码主档信息
exports.getBarcodeDefectData = function (req, res) {
    var parameter = req.body.Parameter,
        BarcodeId = parameter.BarcodeId,
        Work = parameter.Work;

    // var returnData = [];
    var returnData = {
        bizRecordID:0,
        defectDatas:[]
    };
    
    barcodeMasterController.findBarcodeMasterByBarcodeMaster(BarcodeId, function(err,result){
       if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码失败';
                newErr.message = '未找到对应的条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                returnData.bizRecordID = result.BizRecord;                                       
                console.log('result.BizRecord-----------'+result.BizRecord);
                qcRecordController.findAllQCRecords(result.BizRecord, function (err, results) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    }
                    else {
                        if (results == null) {
                            var newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '查询品质记录失败';
                            newErr.message = '未找到对应的品质记录！';
                            res.json({
                                Data: null,
                                Error: newErr
                            });
                        }
                        else {
                            var BadTypeOptions = [];
                            var BadPositionOptions = [];
                            var qcRecords = results;

                            //查找所有的不良类型
                            enumController.findAllExtendEnum("BadType", function (err, result) {
                                if (err) {
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                }
                                else {
                                    if (result == null) {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '查询不良类型失败';
                                        newErr.message = '未找到所有的不良类型！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    }
                                    else {
                                        BadTypeOptions = result.Options;
                                        //查找所有的不良类型
                                        enumController.findAllExtendEnum("BadPosition", function (err, result) {
                                            if (err) {
                                                res.json({
                                                    Data: null,
                                                    Error: err
                                                });
                                            }
                                            else {
                                                if (result == null) {
                                                    var newErr = new Error();
                                                    newErr.leval = 9;
                                                    newErr.title = '查询不良位置失败';
                                                    newErr.message = '未找到所有的不良位置！';
                                                    res.json({
                                                        Data: null,
                                                        Error: newErr
                                                    });
                                                }
                                                else {
                                                    BadPositionOptions = result.Options;
                                                    // var promises = [];
                                                    // results.forEach(function (result) {
                                                    //     promises.push(queryBadTypeAndBadPosition(result));   
                                                    // });
                                                    console.log(qcRecords);
                                                    qcRecords.forEach(function (qcRecord) {
                                                        for (var i = 0; i < BadTypeOptions.length; i++) {
                                                            if (BadTypeOptions[i].Value === qcRecord.BadType) {
                                                                for (var j = 0; j < BadPositionOptions.length; j++) {
                                                                    if (BadPositionOptions[j].Value === qcRecord.BadPosition) {

                                                                        returnData.defectDatas.push({
                                                                            BadType: BadTypeOptions[i].Name,
                                                                            BadTypeValue: BadTypeOptions[i].Value,
                                                                            BadPosition: BadPositionOptions[j].Name,
                                                                            BadPositionValue: BadPositionOptions[j].Value,
                                                                            Description: qcRecord.Description,
                                                                            Status:false,
                                                                            BizRecord: qcRecord.BizRecord
                                                                        })
                                                                    }
                                                                }
                                                                

                                                            }

                                                        }
                                                        
                                                    });
                                                    res.json({
                                                        Data: returnData,
                                                        Error: null
                                                    });

                                                }
                                            }

                                        });

                                    }
                                }

                            });


                        }
                    }

                });
            }
        }
    });

    
};




//检验作业提交
exports.submitCheckWork = function (req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        barcodeMaster = parameter.BarcodeMaster,
        ItemMaster = parameter.ItemMaster,
        Terminal = parameter.Terminal,
        TerminalName = parameter.TerminalName,
        Work = parameter.Work,
        WorkName = parameter.WorkName,
        WorkLocation = parameter.WorkLocation,
        WorkLocationName = parameter.WorkLocationName,
        userId = parameter.UserID,
        //0: 合格 1:不合格
        QCStatus = parameter.QCStatus,
        oldQCStatus = parameter.oldQCStatus,
        badRecords = parameter.badRecords,
        ReworkQty = parameter.ReworkQty;
        
        
    var dateNow = Date.now(),
        bizRecord = {
            CollectDateTime: dateNow,
            Users: [userId],
            // BusinessStatus: 1,//业务状态：完成
            QCType: 0,//质检类型：全检
            QCUser: userId,
            QCDateTime: dateNow,
            QCStatus: QCStatus
        };

    //根据物料和作业查找工序
    operationController.findByItemMasterAndWork(ItemMaster, Work, function (err, operationRecord) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            if (operationRecord == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询工序失败';
                newErr.message = '该物料没有找到对应作业的工序！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            }
            else {
                // console.log("工序-------------"+operationRecord);
                bizRecord.BarcodeMaster = barcodeMaster;
                bizRecord.Work = Work;
                bizRecord.WorkName = WorkName;
                bizRecord.WorkLocation = WorkLocation;
                bizRecord.WorkLocationName = WorkLocationName;
                bizRecord.Terminal = Terminal;
                bizRecord.TerminalName = TerminalName;
                bizRecord.Operation = operationRecord._id;
                bizRecord.OperationName = operationRecord.Name;

                //barcodeMaster包含字段：QCStatus、QCReworkOperation、Operation
                //bindContext包含字段：Work、WorkName、WorkLacation、WorkLacationName、User
                // var streambarcodeMaster = {QCStatus: QCStatus, QCReworkOperation: QCReworkOperation, Operation: Operation};
                var bindContext = {
                    Work: Work,
                    WorkName: WorkName,
                    User: userId,
                    WorkLocation: WorkLocation,
                    WorkLocationName: WorkLocationName
                }
                queryBarcodeMaster(barcode).then(function (record) {
                    console.log(record);
                    console.log("一，--------------------------------");
                    console.log(operationRecord);
                    console.log("二，--------------------------------");
                    console.log(bindContext);
                    barcodeMasterController.streamValidation(record, operationRecord, bindContext).then(function (result){
                        writebizRecord(barcode, bizRecord, badRecords, oldQCStatus, ReworkQty).then(function (result) {
                            res.json(result);
                        }, function (err) {
                            res.json({
                                Data: null,
                                Error: err
                            });
                        });
                    },function(error){
                        res.json({
                            Data: null,
                            Error: error
                        });
                    }); 
                },function(error){
                    res.json({
                        Data: null,
                        Error: error
                    });
                });
                

                
            }
        }
    });
};

function queryBarcodeMaster(barcode) {
    var deferred = Q.defer();

    barcodeMasterController.findBarcodeMaster(barcode, function (err, barcodeMaster) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (barcodeMaster == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '无法识别条码';
            newErr.message = '无法识别的条码，请重新扫描！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(barcodeMaster);
    });

    return deferred.promise;
}

function writebizRecord(barcode, bizRecord, badRecords, oldQCStatus, ReworkQty) {
    var deferred = Q.defer();
    //添加流水信息
    bizRecordController.insert(bizRecord, function (err, record) {
        if (err) {
            deferred.reject(err);
            return;
        }
        var updateRecord = {
            Users: bizRecord.Users,
            // BusinessStatus: bizRecord.BusinessStatus,
            QCStatus: bizRecord.QCStatus,
            BizRecord: record._id,
            Work: bizRecord.Work,
            WorkName: bizRecord.WorkName,
            WorkLocation: bizRecord.WorkLocation,
            WorkLocationName: bizRecord.WorkLocationName,
            Terminal: bizRecord.Terminal,
            TerminalName: bizRecord.TerminalName,
            Operation: bizRecord.Operation,
            OperationName: bizRecord.OperationName
        };
        if(oldQCStatus!=4&&bizRecord.QCStatus===4){
            updateRecord.QCReworkOperation = bizRecord.Operation;
            // updateRecord.ReworkQty = ReworkQty+1;
            updateRecord.ReworkQty = ReworkQty ? ReworkQty+1 : 1;
        }
        
        //添加QC记录
        qcRecordController.addQCRecords(record._id, badRecords, function (err, result) {
            if (err) {
                deferred.reject(err);
                return;
            }
            console.log(updateRecord);
            //更新主档信息
            barcodeMasterController.updateByValue(barcode, updateRecord, function (err, result) {
                if (err) {
                    deferred.reject(err);
                    return;
                }
                if (result.ok === 1) {
                    deferred.resolve({
                        Data: true,
                        Error: null
                    });
                }

            });
        });
    });
    return deferred.promise;
}
